<template>
  <main>
    <div class="chart-content">
      <div class="chart-top">
        <input type="text"
               placeholder="输入图表名称"
               v-model="chartName"
               class="el-input__inner" />
        <i class="el-icon-view"
           title="预览"
           @click="getChartData"></i>
        <i class="el-icon-finished"
           title="保存"
           @click="saveImage"></i>
      </div>
      <div class="
           chart-bottom">
        <aside>
          <el-select v-model="currentTable"
                     placeholder="请选择连接的表"
                     size="small"
                     style="width:100%;"
                     @change="getFields">
            <el-option-group v-for="group in tableOptions"
                             :key="group.label"
                             :label="group.label">
              <el-option v-for="item in group.options"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-option-group>
          </el-select>
          <draggable :list="fieldList"
                     @end="move"
                     :options="{group:{name:'fields',pull:'clone'},dragClass:'ghost',sort: false,put:false}">
            <transition-group>
              <div v-for="item in fieldList"
                   :key="item.name"
                   :id="item.name"
                   class="tag">
                {{item.name}}
              </div>
            </transition-group>
          </draggable>
        </aside>
        <div class="chart-container">
          <div class="dimension">
            <div class="dimension-line">
              <label for="">行维度：</label>
              <div class="lines">
                <draggable :list="xFieldList"
                           @start="start"
                           @end="end"
                           :options="{group:xGroupName,disabled:false}">
                  <transition-group class="x-dimension">
                    <el-tag size="medium"
                            v-for="(item,index) in xFieldList"
                            :key="item.name+index"
                            @close="handleClose(index,'x')"
                            closable>{{item.name}}
                      <el-dropdown :hide-on-click="false"
                                   placement="bottom"
                                   trigger="click">
                        <i class="el-icon-arrow-down el-icon--right"></i>
                        <el-dropdown-menu slot="dropdown">
                          <el-dropdown-item>
                            <label style="display:inline-block;width:0.6rem;">别名：</label>
                            <input type="text"
                                   placeholder="字段别名"
                                   v-model="item.description"
                                   class="el-input__inner"
                                   style="width:1rem;padding:0.1rem;" />
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </el-dropdown>
                    </el-tag>
                  </transition-group>
                </draggable>
                <div class="line"></div>
              </div>
            </div>
            <div class="dimension-line">
              <label for="">列维度：</label>
              <div class="lines">
                <draggable :list="yFieldList"
                           :model="yFieldList"
                           @start="start"
                           @end="end"
                           :options="{group:yGroupName,disabled:false}">
                  <transition-group class="y-dimension">
                    <el-tag size="medium"
                            v-for="(item,index) in yFieldList"
                            :key="item.name+index"
                            @close="handleClose(index,'y')"
                            closable>{{item.name}}
                      <slot>
                        <el-dropdown :hide-on-click="false"
                                     trigger="click"
                                     placement="bottom"
                                     ref="yTag"
                                     :tabindex="index"
                                     :key="'yTag'+item.name+index">
                          <i class="el-icon-arrow-down el-icon--right"
                             :key="item.name+index"></i>
                          <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item>
                              <label style="display:inline-block;width:0.7rem">别名：</label>
                              <input type="text"
                                     placeholder="字段别名"
                                     v-model="item.description"
                                     class="el-input__inner"
                                     style="width:1rem;height:0.3rem;"
                                     @change="changeFieldDescription($event,index)" />
                            </el-dropdown-item>
                            <el-dropdown-item display="position:absoulte;">
                              <label style="display:inline-block;width:0.7rem">聚合函数：</label>
                              <!-- <input type="text"
                                     placeholder="聚合变量"
                                     v-model="item.valueType"
                                     class="el-input__inner"
                                     style="width:1rem;height:0.3rem;" /> -->
                              <el-select v-model="item.valueType"
                                         placeholder="请选择"
                                         style="width:1rem;height:0.3rem; "
                                         trigger="click">
                                <el-option v-for="option in item.valueOptions"
                                           :key="option.value"
                                           :label="option.label"
                                           :value="option.value"
                                           @click.native="changeValue($event,option.value,index)">
                                </el-option>
                              </el-select>
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </el-dropdown>
                      </slot>
                    </el-tag>
                  </transition-group>
                </draggable>
                <div class="
                                         line">
                </div>
              </div>
            </div>
          </div>
          <div class="main-content">
            <table-component :chartData="chartData"
                             :chartTitle="config.chartTitle"
                             ref='table'
                             v-if="config.chartType==1"></table-component>
            <bar-component :chartData="chartData"
                           :chartTitle="config.chartTitle"
                           :chartColor="config.colorList"
                           ref='bar'
                           v-if="config.chartType==2"></bar-component>
            <line-component :chartData="chartData"
                            :chartTitle="config.chartTitle"
                            :chartColor="config.colorList"
                            ref='line'
                            v-if="config.chartType==3"></line-component>
            <pie-component :chartData="chartData"
                           :chartTitle="config.chartTitle"
                           :chartColor="config.colorList"
                           ref='pie'
                           v-if="config.chartType==4"></pie-component>
          </div>
        </div>
        <el-dialog :title="config.title"
                   :visible.sync="config.dialogFormVisible">
          <el-form>
            <el-form-item label="添加筛选条件"
                          style="margin-left:0.3rem;margin-bottom:0.3rem;">
              <el-button type="primary"
                         size="small"
                         icon="el-icon-plus"
                         title="添加筛选条件"
                         style="margin-left:-5.6rem"
                         @click="addCondition()">
              </el-button>
            </el-form-item>
            <el-form-item style="margin-left:-1.1rem;margin-bottom:0.2rem"
                          v-for="(condition,index) in config.conditions"
                          :key="index">
              <el-select v-model="condition.field"
                         placeholder="字段"
                         style="width:2rem;margin-left:0.5rem;margin-right:0.2rem">
                <el-option v-for="item in config.fieldOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-select v-model="condition.symbol"
                         placeholder="符号"
                         style="width:1rem;margin-right:0.2rem;margin-left:0.2rem;">
                <el-option v-for="item in config.symbolOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <input type="text"
                     placeholder="值"
                     v-model="condition.value"
                     class="el-input__inner"
                     style="width:2rem;height:0.4rem;margin-right:0.5rem;margin-left:0.2rem;" />
              <i class="el-icon-circle-close"
                 @click="deleteCondition(index)"></i>
            </el-form-item>
          </el-form>
          <div slot="footer"
               class="dialog-footer">
            <el-button type="primary"
                       @click="config.dialogFormVisible = false">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 配色方案弹窗 -->
        <el-dialog title="配色方案"
                   style="top:-0.6rem;"
                   :visible.sync="config.colorEditVisible">
          <el-form>
            <el-form-item label="添加配色"
                          style="margin-left:0.3rem;margin-bottom:0.1rem;">
              <el-button type="primary"
                         size="small"
                         icon="el-icon-plus"
                         title="添加配色"
                         style="margin-left:-5.6rem"
                         @click="addColor()">
              </el-button>
            </el-form-item>
            <el-form-item style="margin-left:0.3rem;margin-bottom:0.02rem"
                          :label="'配色'+(index+1)"
                          v-for="(color,index) in config.colorList"
                          :key="index">
              <el-color-picker v-model="color.value"
                               style="display:inline-block;margin-left:-1.7rem;margin-right:2rem;"></el-color-picker>
              <i class="el-icon-circle-close"
                 style="vertical-align:top;margin-top:0.15rem;"
                 @click="deleteColor(index)"></i>
            </el-form-item>
          </el-form>
          <div slot="footer"
               class="dialog-footer">
            <el-button type="primary"
                       @click="saveColor">确 定</el-button>
          </div>
        </el-dialog>
        <aside class="config">
          <h3>图表配置</h3>
          <ul>
            <li>
              <label>图表标题</label>
              <el-input type="textarea"
                        placeholder="标题"
                        v-model="config.chartTitle"
                        :autosize="{ minRows: 3, maxRows: 4 }"
                        @change="changeChartTitle" />
            </li>
            <li>
              <label>图表类型</label>
              <el-select v-model="config.chartType"
                         placeholder="请选择">
                <el-option v-for="item in config.chartOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </li>
            <li>
              <label>数据记录</label>
              <el-select v-model="config.dataNum"
                         placeholder="请选择">
                <el-option v-for="item in config.numberOptions"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </li>
            <li>
              <label for="">筛选条件</label>
              <el-button type="primary"
                         size="small"
                         icon="el-icon-plus"
                         @click="config.dialogFormVisible=true"></el-button>
            </li>
            <li v-if="config.chartType!=1">
              <label for="">配色方案</label>
              <el-button type="primary"
                         size="small"
                         icon="el-icon-edit"
                         title="默认为系统自定义配色"
                         @click="getColor"></el-button>
            </li>
          </ul>
        </aside>
      </div>
    </div>
  </main>
</template>
<script>
import draggable from 'vuedraggable'
import domtoimage from 'dom-to-image'
import TableComponent from './component/TableComponent'
import BarComponent from './component/BarComponent'
import LineComponent from './component/LineComponent'
import PieComponent from './component/PieComponent'
export default {
  name: 'ChartLevel',
  components: {
    draggable,
    TableComponent,
    BarComponent,
    LineComponent,
    PieComponent
  },
  mounted () {
    this.$on('connectUpdate', (val, form) => {
      this.connectUpdate(val, form)
    });
  },
  data () {
    return {
      chartName: '',
      currentTable: '',
      tableOptions: [],
      xGroupName: 'fields',
      yGroupName: 'fields',
      xFieldList: [],
      yFieldList: [],
      fieldList: [],
      config: {
        chartTitle: '',
        chartType: 1,
        chartOptions: [
          { label: '表格', value: 1 },
          { label: '柱状图', value: 2 },
          { label: '折线图', value: 3 },
          { label: '饼状图', value: 4 }
        ],
        dataNum: '',
        numberOptions: [
          { label: '10', value: 1 },
          { label: '20', value: 2 },
          { label: '30', value: 3 },
          { label: '50', value: 4 },
        ],
        title: '筛选条件',
        dialogFormVisible: false,
        conditions: [],
        fieldOptions: [
          { label: 'id', value: 'id' },
          { label: 'name', value: 'name' },
          { label: 'phone', value: 'phone' },
          { label: 'address', value: 'address' }
        ],
        symbolOptions: [
          { label: '>', value: '>' },
          { label: '=', value: '=' },
          { label: '<', value: '<' },
          { label: 'include', value: 'like' }
        ],
        colorEditVisible: false,
        colorList: []
      },
      valueOptions: [
        { label: '原始值', value: '原始值' },
        { label: 'count', value: 'count' },
        { label: 'max', value: 'max' },
        { label: 'min', value: 'min' },
        { label: 'avg', value: 'avg' }
      ],
      chartData: {},
    }
  },
  methods: {
    // 判断数据库是否连接
    connectUpdate (val, form) {
      let self = this
      self.isconnect = val
      if (self.isconnect) {
        self.$ajax({
          method: 'POST',
          url: '/view/getTable/',
          dataType: 'json',
          data: {
            'database': form.db,
            'userName': sessionStorage.getItem('name')
          }
        }).then(function (response) {
          console.log(response.data.data)
          self.tableOptions = [];
          self.tableOptions.push({
            label: `当前数据库是:${form.db}`,
            options: response.data.data.map(function (item) {
              return { label: item.label, value: item.label }
            })
          })
        }).catch(function (err) {
          console.log(err)
        })
      } else {
        self.tableOptions = [];
        self.currentTable = '';
        self.fieldList = [];
      }
    },
    //获取字段信息
    getFields (value) {
      let self = this
      console.log(value);
      self.$ajax({
        method: 'POST',
        url: '/view/getTableColumn/',
        dataType: 'json',
        data: {
          'tableName': value
        }
      }).then(function (response) {
        self.fieldList = response.data.data.map(function (item) { return { name: item } });
        self.config.fieldOptions = response.data.data.map(function (item) { return { label: item, value: item } });
        self.conditions = [];
      }).catch(function (err) {
        console.log(err)
      })
    },
    // tag相关
    start (ev) {
      let self = this
      let name = ev.from.className
      switch (name) {
        case 'x-dimension': self.xGroupName = '1'; break;
        case 'y-dimension': self.yGroupName = '1'; break;
      }
      console.log(ev.from.className);
      // self.xFieldList.push(self.fieldList[ev.oldIndex])
    },
    end (ev) {
      let self = this
      let name = ev.from.className
      let oldIndex = ev.oldIndex
      let newIndex = ev.newIndex
      // let item = ""
      console.log("oldIndex", oldIndex)
      console.log("newIndex", newIndex)
      console.log(self.$refs.yTag)
      switch (name) {
        case 'x-dimension':
          self.xGroupName = 'fields';
          break;
        case 'y-dimension':
          self.yGroupName = 'fields';
          // setTimeout(function () {
          //   item = self.$refs.yTag.splice(oldIndex, 1);
          //   console.log(item)
          //   self.$refs.yTag.splice(newIndex, 0, item[0]);
          // })
          break;
      }
      console.log(self.$refs.yTag)
      self.$forceUpdate()
    },
    move (ev) {
      let self = this
      let name = ev.to.className
      console.log(name)
      console.log(ev.newIndex)
      switch (name) {
        case 'x-dimension':
          self.xFieldList[ev.newIndex] = { name: self.xFieldList[ev.newIndex].name, description: '' };
          break;
        case 'y-dimension':
          self.yFieldList[ev.newIndex] = { name: self.yFieldList[ev.newIndex].name, description: '', valueType: '原始值', valueOptions: self.valueOptions };
          break;
      }
      self.$forceUpdate()
    },
    changeFieldDescription (e, index) {
      // self.yFieldList[index]
      let self = this
      console.log(e.target.value)
      console.log(self.yFieldList[index])
    },
    changeValue (e, value, index) {
      let self = this
      console.log(index)
      console.log(self.$refs.yTag)
      self.yFieldList[index].valueType = value
      console.log(self.yFieldList)
      self.$nextTick(() => {
        self.$refs.yTag[index].show()
      })
      self.$forceUpdate()
      console.log(self.yFieldList)
    },
    handleClose (index, mode) {
      let self = this
      switch (mode) {
        case 'x': self.xFieldList.splice(index, 1); break;
        case 'y': self.yFieldList.splice(index, 1); break;
      }
    },
    // 筛选条件相关
    addCondition () {
      let self = this;
      self.config.conditions.push({
        'field': '', 'symbol': '', 'value': ''
      });
    },
    deleteCondition (index) {
      let self = this
      self.config.conditions.splice(index, 1);
    },
    //配色方案相关
    addColor () {
      let self = this;
      if (self.config.colorList.length == 8) {
        self.$message.error('配色不能超过8种')
      }
      else self.config.colorList.push({
        value: ''
      });
    },
    deleteColor (index) {
      let self = this
      self.config.colorList.splice(index, 1);
    },
    getColor () {
      let self = this
      self.$ajax({
        method: 'POST',
        url: '/view/getColor/',
        dataType: 'json',
        data: {
          user: sessionStorage.getItem('name')
        }
      }).then(function (response) {
        console.log(response.data)
        if (response.data.colorList.length == 0) {
          self.config.colorList = ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a']
            .map(function (item) {
              return { value: item }
            })
        }
        else self.config.colorList = response.data.colorList.map(function (item) {
          return { value: item }
        })
        self.config.colorEditVisible = true
      }).catch(function (err) {
        console.log(err)
      })
    },
    saveColor () {
      let self = this;
      self.$ajax({
        method: 'POST',
        url: '/view/saveColor/',
        dataType: 'json',
        data: {
          user: sessionStorage.getItem('name'),
          colorList: self.config.colorList.map(function (item) { return item.value })
        }
      }).then(function (response) {
        console.log(response)
        self.config.colorEditVisible = false
        self.$message({ message: '配色方案保存成功', type: 'success' })
        switch (self.config.chartType) {
          case 2: self.$refs.bar.$emit('updateColor', self.config.colorList); break;
          case 3: self.$refs.line.$emit('updateColor', self.config.colorList); break;
          case 4: self.$refs.pie.$emit('updateColor', self.config.colorList); break;
        }
      }).catch(function (err) {
        console.log(err)
      })
    },
    getChartData () {
      let self = this
      self.$ajax({
        method: 'POST',
        url: '/view/getChartData/',
        dataType: 'json',
        data: {
          tableName: self.currentTable,
          xDimension: self.xFieldList,
          yDimension: self.yFieldList,
          conditions: self.config.conditions
        }
      }).then(function (response) {
        let data = response.data
        self.chartData.xFieldData = data.xFieldData
        self.chartData.yFieldData = data.yFieldData
        self.chartData.xTitle = self.xFieldList
        self.chartData.yTitle = self.yFieldList
        console.log(self.config.chartType)
        switch (self.config.chartType) {
          case 1: self.$refs.table.$emit('updateData', self.chartData); break;
          case 2: self.$refs.bar.$emit('updateData', self.chartData); break;
          case 3: self.$refs.line.$emit('updateData', self.chartData); break;
          case 4: self.$refs.pie.$emit('updateData', self.chartData); break;
        }
      }).catch(function (err) {
        console.log(err)
      })
    },
    saveImage () {
      let self = this;
      let node = document.querySelector('.main-content');
      console.log(node);
      domtoimage.toPng(node, { bgcolor: '#fff' })
        .then((dataUrl) => {
          console.log(dataUrl)
          // this.img = dataUrl;
          // let img = new Image();
          // img.src = dataUrl;
          // let formData = new FormData(img);
          self.$ajax({
            method: 'POST',
            url: '/view/saveImage/',
            data: {
              img: dataUrl,
              name: self.chartName,
              user: sessionStorage.getItem('name')
            },
            dataType: 'json'
          }).then(function (response) {
            console.log(response);
            self.$message({ type: 'success', message: '图表保存成功' })
          })
            .catch(function (err) {
              console.log(err);
            })
        })
        .catch(function (error) {
          console.error('oops, something went wrong!', error);
        });
    },
    changeChartTitle (value) {
      let self = this
      switch (self.config.chartType) {
        case 1: self.$refs.table.$emit('updateTitle', value); break;
        case 2: self.$refs.bar.$emit('updateTitle', value); break;
        case 3: self.$refs.line.$emit('updateTitle', value); break;
        case 4: self.$refs.pie.$emit('updateTitle', value); break;
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
main
  display flex
  height 100%
  padding 0
  .chart-content
    flex 1
    height 100%
    background red
    .chart-top
      width 100%
      height 0.25rem
      background #e6e6e6
      border-bottom 0.01rem solid #fff
      font-size 0.15rem
      .el-input__inner
        width 2rem
        height 0.24rem
        margin-left -0.2rem
        margin-right 7.6rem
      i
        display inline-block
        margin-right 0.2rem
        cursor pointer
      i:hover
        color #3689ff
    .chart-bottom
      display flex
      width 100%
      height 7.1rem
      background #fff
      aside
        display inline-block
        width 2.5rem
        height 100%
        border 0.01rem solid #e6e6e6
        user-select none
        .el-select
          width 100%
        .tag
          display inline-block
          width 100%
          height 0.5rem
          cursor pointer
          line-height 0.5rem
          border 0.01rem solid #ecf5ff
        .tag:hover
          background #ecf5ff
          color #409eff
      .chart-container
        flex 1
        .dimension
          width 96%
          padding-right 0.5rem
          .dimension-line
            width 100%
            height 0.5rem
            margin-top 0.2rem
            margin-bottom 0.2rem
            line-height 0.5rem
            label
              font-size 0.18rem
              line-height 0.5rem
              user-select none
            .lines
              display inline-block
              width 8rem
              height 0.5rem
              .line
                width 100%
                height 0.02rem
                background #e6e6e6
              .x-dimension, .y-dimension
                display flex
                width 100%
                height 0.4rem
                padding-left 0.1rem
                padding-top 0.1rem
                .el-tag
                  display inline-block
                  margin-left 0.03rem
                  margin-right 0.03rem
                  cursor pointer
                  height 0.3rem
                  min-width 0.5rem
        .main-content
          box-sizing border-box
          width 10.5rem
          height 5.5rem
          padding 0.3rem
          border 0.01rem solid #e6e6e6
          border-radius 1%
      .config
        h3
          margin-top 0.2rem
          font-size 0.18rem
        ul
          list-style none
          padding 0
          margin-top 0.5rem
          li
            display flex
            margin-top 0.3rem
            label
              line-height 0.4rem
              margin-left 0.2rem
              margin-right 0.3rem
              font-size 0.14rem
            .el-select
              width 1rem
            .el-textarea
              width 1rem !important
.sortable-ghost
  display inline-block
  min-width 0.5rem
  line-height 0.27rem
  height 0.27rem
  background #ecf5ff
  color #409eff
  margin-left 0.03rem
  margin-right 0.03rem
  border 0.01rem solid #e6e6e6
.el-input__inner
  height 0.3rem
.el-icon-circle-close
  cursor pointer
.el-icon-circle-close:hover
  color red
/deep/.el-color-picker__trigger
  width 2rem !important
</style>